/*
Copyright (C) 2012 John Tsiombikas <nuclear@member.fsf.org>,
                   Ioannis Makris <imak@imak.gr>

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "glory.h"
#include "gloin.h"
#include "wsys.h"
#include "log.h"

#include <stdio.h>

#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>

#define PENDING_CREATE		1

#define CLASS_NAME	"glorywin"
#define WIN_STYLE	(WS_BORDER | WS_CAPTION | WS_MINIMIZEBOX | WS_POPUP | WS_SYSMENU | WS_VISIBLE)

struct wsys_window {
	HWND win;
	HDC dc;
	HGLRC ctx;
	int width, height;
	unsigned int pending;
};

static int quit;

static long __stdcall handle_events(HWND w, unsigned int msg, unsigned int wparam, long lparam);
static int mouse_button(unsigned int msg);

static void calc_win_size(int xsz, int ysz, int *cxsz, int *cysz, int *posx, int *posy);
static void attr_to_pfd(PIXELFORMATDESCRIPTOR *pfd, struct gloin_attr *gattr);
static void mask_to_pfd(PIXELFORMATDESCRIPTOR *pfd, unsigned int mask);
static void print_pfd_info(PIXELFORMATDESCRIPTOR *pfd);


int gloin_wsys_init(void)
{
	WNDCLASS wclass;
	HINSTANCE pid;

	quit = 0;
	pid = GetModuleHandle(0);

	memset(&wclass, 0, sizeof wclass);
	wclass.style = CS_VREDRAW | CS_HREDRAW | CS_OWNDC;
	wclass.lpfnWndProc = handle_events;
	wclass.hInstance = pid;
	wclass.lpszClassName = CLASS_NAME;

	if(!RegisterClass(&wclass)) {
		gloin_log("%s: failed to register window class\n", __FUNCTION__);
		return -1;
	}

	return 0;
}

void gloin_wsys_cleanup(void)
{
	UnregisterClass(CLASS_NAME, GetModuleHandle(0));
}

int gloin_wsys_set_video_mode(int xsz, int ysz, int rate)
{
	/* TODO */
	return -1;
}

int gloin_wsys_get_video_mode(int *xsz, int *ysz, int *rate)
{
	/* TODO */
	return -1;
}

int gloin_wsys_create_window(struct window *win, int xsz, int ysz, unsigned int mode)
{
	int xpos, ypos, pf_idx;
	unsigned int style;
	PIXELFORMATDESCRIPTOR pfd;
	struct wsys_window *wswin = 0;

	if(!(wswin = malloc(sizeof *wswin))) {
		gloin_log("%s: failed to allocate memory\n", __FUNCTION__);
		return -1;
	}

	calc_win_size(xsz, ysz, &wswin->width, &wswin->height, &xpos, &ypos);
	style = WIN_STYLE;

	if(!(wswin->win = CreateWindow(CLASS_NAME, "Glorious Window (W32)", style, xpos, ypos,
			wswin->width, wswin->height, 0, 0, GetModuleHandle(0), 0))) {
		gloin_log("%s: failed to create window\n", __FUNCTION__);
		goto err;
	}
	ShowWindow(wswin->win, SW_SHOW);
	SetForegroundWindow(wswin->win);
	SetActiveWindow(wswin->win);

	wswin->dc = GetDC(wswin->win);

	if(mode == GLORY_USE_ATTR) {
		attr_to_pfd(&pfd, &gloin_attr);
	} else {
		mask_to_pfd(&pfd, mode);
	}

	if(!(pf_idx = ChoosePixelFormat(wswin->dc, &pfd))) {
		gloin_log("%s: can't find requested pixel format\n", __FUNCTION__);
		goto err;
	}
	print_pfd_info(&pfd);

	if(!SetPixelFormat(wswin->dc, pf_idx, &pfd)) {
		gloin_log("%s: failed to set pixel format\n", __FUNCTION__);
		goto err;
	}
	if(!(wswin->ctx = wglCreateContext(wswin->dc))) {
		gloin_log("%s: failed to create OpenGL context\n", __FUNCTION__);
		goto err;
	}

	wswin->pending = PENDING_CREATE;
	win->wsys_win = wswin;
	return 0;

err:
	free(wswin);
	return -1;
}

void gloin_wsys_destroy_window(struct window *win)
{
	void (*func)() = gloin_get_callback(win, GLORY_DESTROY);
	if(func) {
		gloin_set_active(win);
		func(gloin_get_callback_data(win, GLORY_DESTROY));
	}

	wglDeleteContext(win->wsys_win->ctx);
	ReleaseDC(win->wsys_win->win, win->wsys_win->dc);
	DestroyWindow(win->wsys_win->win);

	free(win->wsys_win);
	win->wsys_win = 0;
}

void gloin_wsys_resize(struct window *win, int xsz, int ysz)
{
	MoveWindow(win->wsys_win->win, 0, 0, xsz, ysz, TRUE);
}

void gloin_wsys_set_size(struct window *win, int xsz, int ysz)
{
	win->wsys_win->width = xsz;
	win->wsys_win->height = ysz;
}

void gloin_wsys_get_size(struct window *win, int *xsz, int *ysz)
{
	*xsz = win->wsys_win->width;
	*ysz = win->wsys_win->height;
}

void gloin_wsys_set_active(struct window *win)
{
	if(win) {
		wglMakeCurrent(win->wsys_win->dc, win->wsys_win->ctx);
	} else {
		wglMakeCurrent(0, 0);
	}
}

void gloin_wsys_resize_window(struct window *win, int width, int height)
{
	int xpos, ypos;

	calc_win_size(width, height, &width, &height, &xpos, &ypos);
	MoveWindow(win->wsys_win->win, xpos, ypos, width, height, TRUE);
}

void gloin_wsys_set_title(struct window *win, const char *str)
{
	SetWindowText(win->wsys_win->win, str);
}

void gloin_wsys_redisplay(struct window *win)
{
	InvalidateRect(win->wsys_win->win, 0, 0);
}

void gloin_wsys_swap_buffers(struct window *win)
{
	SwapBuffers(win->wsys_win->dc);
}

unsigned int gloin_wsys_modifiers(void)
{
	return 0;	/* TODO */
}

void gloin_wsys_set_callback_mask(struct window *win, unsigned int cbmask)
{
	/* not needed */
}

void gloin_wsys_quit(void)
{
	quit = 1;
}

int glory_process_events(void)
{
	int i, have_idle, ret = 0;
	MSG msg;
	struct window *win;

	/* loop through all the windows to call any pending create callbacks */
	win = gloin_winlist();
	while(win) {
		if(win->wsys_win->pending & PENDING_CREATE) {
			gloin_call_create(win);
			win->wsys_win->pending &= ~PENDING_CREATE;
		}
		win = win->next;
	}

	have_idle = gloin_have_idle();

	i = 0;
	while(!quit) {
		if(i++ > 0 || have_idle) {
			if(!PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
				break;
			}
		} else {
			if(!GetMessage(&msg, 0, 0, 0)) {
				return -1;
			}
		}

		if(msg.message == WM_QUIT) {
			return -1;
		}
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	if(have_idle) {
		gloin_call_idle();
	}
	return 0;
}

void gloin_wsys_event_loop(void)
{
	while(!quit) {
		if(glory_process_events() == -1) {
			break;
		}
	}
}

static long __stdcall handle_events(HWND w, unsigned int msg, unsigned int wparam, long lparam)
{
	int state;
	void (*func)();
	void *cls;
	struct window *win;
	static int bnaccum;

	/* find the glory window corresponding to this HWND */
	win = gloin_winlist();
	while(win) {
		if(win->wsys_win->win == w) {
			break;
		}
		win = win->next;
	}
	if(!win) {
		gloin_log("%s: got event for unknown window\n", __FUNCTION__);
		return DefWindowProc(w, msg, wparam, lparam);
	}

	switch(msg) {
	case WM_PAINT:
		if((func = gloin_get_callback(win, GLORY_DISPLAY))) {
			gloin_set_active(win);
			func(gloin_get_callback_data(win, GLORY_DISPLAY));
		}
		ValidateRect(w, 0);
		break;

	case WM_CLOSE:
		glory_destroy_window(win->id);
		break;

	case WM_KEYDOWN:
	case WM_KEYUP:
		if((func = gloin_get_callback(win, GLORY_KEYBOARD))) {
			void *cls = gloin_get_callback_data(win, GLORY_KEYBOARD);
			gloin_set_active(win);
			func(MapVirtualKey(wparam, 2), msg == WM_KEYDOWN, cls);
		}
		break;

	case WM_LBUTTONDOWN:
	case WM_RBUTTONDOWN:
	case WM_MBUTTONDOWN:
		if(1) {
			state = 1;
			bnaccum++;
		} else {
	case WM_LBUTTONUP:
	case WM_RBUTTONUP:
	case WM_MBUTTONUP:
			state = 0;
			bnaccum--;
		}
		if((func = gloin_get_callback(win, GLORY_MOUSE))) {
			win->mouse_index = 0;
			gloin_set_active(win);
			func(mouse_button(msg), state, LOWORD(lparam), HIWORD(lparam));
		}
		break;

	case WM_MOUSEMOVE:
		if(bnaccum) {
			if((func = gloin_get_callback(win, GLORY_MOTION))) {
				cls = gloin_get_callback_data(win, GLORY_MOTION);
			}
		} else {
			if((func = gloin_get_callback(win, GLORY_PASSIVE))) {
				cls = gloin_get_callback_data(win, GLORY_PASSIVE);
			}
		}
		if(func) {
			win->mouse_index = 0;
			gloin_set_active(win);
			func(LOWORD(lparam), HIWORD(lparam), cls);
		}
		break;

	default:
		return DefWindowProc(w, msg, wparam, lparam);
	}
	return 0;
}

static int mouse_button(unsigned int msg)
{
	switch(msg) {
	case WM_LBUTTONDOWN:
	case WM_LBUTTONUP:
		return GLORY_LEFT_BUTTON;

	case WM_RBUTTONDOWN:
	case WM_RBUTTONUP:
		return GLORY_RIGHT_BUTTON;

	case WM_MBUTTONDOWN:
	case WM_MBUTTONUP:
		return GLORY_MIDDLE_BUTTON;

	default:
		break;
	}
	return -1;
}

static void calc_win_size(int xsz, int ysz, int *cxsz, int *cysz, int *posx, int *posy)
{
	RECT rect;
	DEVMODE dmode;

	rect.left = rect.top = 0;
	rect.right = xsz;
	rect.bottom = ysz;

	AdjustWindowRect(&rect, WIN_STYLE, 0);

	*cxsz = rect.right - rect.left;
	*cysz = rect.bottom - rect.top;

	*posx = *posy = 0;

	memset(&dmode, 0, sizeof dmode);
	dmode.dmSize = sizeof dmode;

	if(EnumDisplaySettings(0, ENUM_CURRENT_SETTINGS, &dmode)) {
		int x, y;

		x = (dmode.dmPelsWidth - *cxsz) / 2;
		if(x > 0) {
			*posx = x;
		}
		y = (dmode.dmPelsHeight - *cysz) / 2;
		if(y > 0) {
			*posy = y;
		}
	}
}

static void attr_to_pfd(PIXELFORMATDESCRIPTOR *pfd, struct gloin_attr *gattr)
{
	memset(pfd, 0, sizeof *pfd);
	pfd->nSize = sizeof *pfd;
	pfd->nVersion = 1;
	pfd->dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;

	pfd->cColorBits = gattr->rbits + gattr->gbits + gattr->bbits;
	pfd->cRedBits = gattr->rbits;
	pfd->cGreenBits = gattr->gbits;
	pfd->cBlueBits = gattr->bbits;

	pfd->cDepthBits = gattr->zbits;
	pfd->cStencilBits = gattr->sbits;

	if(gattr->doublebuf) {
		pfd->dwFlags |= PFD_DOUBLEBUFFER;
	}
	if(gattr->stereo) {
		pfd->dwFlags |= PFD_STEREO;
	}

	/* TODO multisampling? */
}

static void mask_to_pfd(PIXELFORMATDESCRIPTOR *pfd, unsigned int mask)
{
	memset(pfd, 0, sizeof *pfd);
	pfd->nSize = sizeof *pfd;
	pfd->nVersion = 1;
	pfd->dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;

	pfd->cColorBits = 24;
	pfd->cRedBits = 8;
	pfd->cGreenBits = 8;
	pfd->cBlueBits = 8;

	if(mask & GLORY_DOUBLE) {
		pfd->dwFlags |= PFD_DOUBLEBUFFER;
	}
	if(mask & GLORY_DEPTH) {
		pfd->cDepthBits = 24;
	}
	if(mask & GLORY_STENCIL) {
		pfd->cStencilBits = 8;
	}
	if(mask & GLORY_STEREO) {
		pfd->dwFlags |= PFD_STEREO;
	}

	/* TODO multisampling? */
}

static void print_pfd_info(PIXELFORMATDESCRIPTOR *pfd)
{
	gloin_log("got pixel format: %d%d%d", pfd->cRedBits, pfd->cGreenBits, pfd->cBlueBits);
	gloin_log(" d:%d s:%d", pfd->cDepthBits, pfd->cStencilBits);
	gloin_log(" %s", (pfd->dwFlags & PFD_STEREO) ? "stereo" : "mono");
	gloin_log(" samples/pixel: %d\n", 1);	/* TODO */
}
